import { useEffect } from 'react';
import { View, Input, Button } from '@tarojs/components';
import { useState } from 'react';
import { useRouter, navigateBack } from '@tarojs/taro';
import { useDispatch, useSelector } from 'react-redux';
import { setAddress } from '@/store/address';
import { RootState } from '@/store';

import { AddressType } from '@/utils/address';
import './index.less';
import Taro from '@tarojs/taro';
import request from '@/utils/request';
import { getUser } from '@/utils/user';

export default function Index() {
  const user = getUser();
  const router = useRouter();
  const dispatch = useDispatch();
  const addressState = useSelector((state: RootState) => state.address);
  // 如果没有地址数据，默认进入编辑状态
  const [isEditing, setIsEditing] = useState(!addressState.community);
  
  // 编辑状态的临时数据
  const [community, setCommunity] = useState(addressState.community);
  const [building, setBuilding] = useState(addressState.building);
  const [unit, setUnit] = useState(addressState.unit);
  const [room, setRoom] = useState(addressState.room);

  const type = router.params?.type as AddressType;

  useEffect(() => {
    console.log("user",user);
    if (user) {
      setCommunity(user.community);
      setBuilding(user.building);
      setUnit(user.unit);
      setRoom(user.room);

      dispatch(setAddress({
        community: user.community,
        building: user.building,
        unit: user.unit,
        room: user.room,
      }));
    }
  }, []);

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleSave = () => {
    if (!community || !building || !room) {
      Taro.showToast({
        title: '请填写小区名称、楼栋号和门牌号',
        icon: 'none',
      });
      return;
    }

    const saveAddress = async () => {
      // 调用接口保存地址
      const res = await request.post('/user/save-address', {
        community,
        building,
        unit,
        room,
        userId: user?.id,
      });
      console.log("res",res);
      if (res) {
        Taro.showToast({
          title: '保存成功',
          icon: 'success',
        });
        // 保存到 store
        dispatch(setAddress({
          community,
          building,
          unit,
          room,
        }));
        setIsEditing(false);

        if (type === AddressType.BACK) {
          navigateBack();
        }
      }
    }
    saveAddress();

    
  };

  const handleCancel = () => {
    // 取消编辑，恢复store中的数据
    setCommunity(addressState.community);
    setBuilding(addressState.building);
    setUnit(addressState.unit);
    setRoom(addressState.room);
    setIsEditing(false);
    if (type === AddressType.BACK) {
      navigateBack();
    }
  };

  return (
    <View className="fill-address">
      <View className="content">
        <View className="form-item">
          <View className="label">小区名称</View>
          <Input 
            className="input"
            type="text"
            value={community}
            onInput={e => setCommunity(e.detail.value)}
            placeholder="请填入您居住的小区名称"
            placeholderClass="placeholder"
            disabled={!isEditing}
          />
        </View>

        <View className="form-item">
          <View className="label">楼栋号</View>
          <Input 
            className="input"
            type="text"
            value={building}
            onInput={e => setBuilding(e.detail.value)}
            placeholder="请填入您的楼栋号码"
            placeholderClass="placeholder"
            disabled={!isEditing}
          />
        </View>

        <View className="form-item unit-room">
          <View className="unit">
            <Input 
              className="input"
              type="text"
              value={unit}
              onInput={e => setUnit(e.detail.value)}
              placeholder="单元"
              placeholderClass="placeholder"
              disabled={!isEditing}
            />
          </View>
          <View className="separator">-</View>
          <View className="room">
            <Input 
              className="input"
              type="text"
              value={room}
              onInput={e => setRoom(e.detail.value)}
              placeholder="门牌号"
              placeholderClass="placeholder"
              disabled={!isEditing}
            />
          </View>
        </View>

        <View className="tips">
          *您的住址信息仅用于多多帮服务使用，住址变更时可至「我的-居住地址」中更新
        </View>
      </View>

      <View className="footer">
        {isEditing ? (
          <View className="button-group">
            <Button 
              className="btn btn-cancel" 
              onClick={handleCancel}
            >
              <View className="button-content">
                <View className="text">取消</View>
              </View>
            </Button>
            <Button 
              className="btn btn-save" 
              onClick={handleSave}
            >
              <View className="button-content">
                <View className="text">保存</View>
              </View>
            </Button>
          </View>
        ) : (
          <Button 
            className="btn btn-edit" 
            onClick={handleEdit}
          >
            <View className="button-content">
              <View className="text">修改</View>
            </View>
          </Button>
        )}
      </View>
    </View>
  );
}
